import os
import subprocess
from pathlib import Path

from src.utils.log import Log
from src.utils.utils import Utils


def generate_sudoers_config(username=None):
    """
    生成sudoers配置文件内容
    
    :param username: 用户名，如果为None则使用当前用户
    :return: (配置内容, 配置文件路径)
    """
    try:
        if not username:
            # 获取当前用户名
            result = subprocess.run(['whoami'], capture_output=True, text=True)
            username = result.stdout.strip()
        
        # sudoers配置内容，允许执行特定命令无需密码
        config_content = f"""# Auto-clock sudoers configuration
# Generated by auto-clock application
{username} ALL=(ALL) NOPASSWD: /usr/bin/systemctl suspend, /usr/bin/systemctl hibernate, /usr/sbin/shutdown, /sbin/shutdown, /usr/bin/pm-suspend, /usr/sbin/pm-suspend, /usr/bin/systemctl restart NetworkManager, /usr/bin/systemctl restart networking, /sbin/ip, /bin/ip, /usr/sbin/ip, /usr/bin/nmcli, /usr/sbin/nmcli
"""
        
        # 配置文件保存到用户目录
        config_path = Path.home() / "auto-clock-sudoers"
        
        return config_content, str(config_path)
        
    except Exception as e:
        Log.error(f"生成sudoers配置失败: {str(e)}")
        raise Exception(f"生成sudoers配置失败: {str(e)}")


def save_sudoers_config(username=None):
    """
    保存sudoers配置文件到用户目录
    
    :param username: 用户名
    :return: 配置文件路径
    """
    try:
        config_content, config_path = generate_sudoers_config(username)
        
        with open(config_path, 'w', encoding='utf-8') as f:
            f.write(config_content)
        
        Log.info(f"sudoers配置文件已保存到: {config_path}")
        return config_path
        
    except Exception as e:
        Log.error(f"保存sudoers配置失败: {str(e)}")
        raise Exception(f"保存sudoers配置失败: {str(e)}")


def check_sudo_permission():
    """
    检查当前用户是否有sudo权限（无需密码执行特定命令）
    
    :return: (是否有权限, 状态信息)
    """
    try:
        # 尝试使用sudo执行一个无害的命令来检查权限
        test_commands = [
            '/usr/bin/systemctl --version',
            '/usr/sbin/shutdown --version'
        ]
        
        for cmd in test_commands:
            try:
                result = subprocess.run(
                    ['sudo', '-n', cmd], 
                    capture_output=True, 
                    text=True, 
                    timeout=5
                )
                if result.returncode == 0:
                    return True, "sudo权限配置正常"
            except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError):
                continue
        
        # 检查sudoers文件中是否有相关配置
        username = subprocess.run(['whoami'], capture_output=True, text=True).stdout.strip()
        try:
            result = subprocess.run(
                ['sudo', '-n', 'cat', '/etc/sudoers.d/auto-clock'], 
                capture_output=True, 
                text=True, 
                timeout=5
            )
            if result.returncode == 0 and username in result.stdout and 'NOPASSWD' in result.stdout:
                return True, "sudo权限配置正常"
        except:
            pass
        
        return False, "sudo权限未配置或需要密码"
        
    except Exception as e:
        Log.error(f"检查sudo权限失败: {str(e)}")
        return None, f"检查权限时出错: {str(e)}"


def get_sudo_install_commands(config_path):
    """
    获取安装sudoers配置的命令
    
    :param config_path: 配置文件路径
    :return: 安装命令列表
    """
    install_commands = [
        f"sudo cp {config_path} /etc/sudoers.d/auto-clock && sudo chmod 440 /etc/sudoers.d/auto-clock && sudo visudo -c"
    ]
    
    return install_commands
